﻿import { Injectable } from '@angular/core';
import { Http, RequestOptionsArgs, Headers } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';

@Injectable()
export class ApiService {
    header: Headers = new Headers();
    constructor(private http: Http, private router: Router) { }

    get(url: string, options: RequestOptionsArgs, success: any, failure: any) {
        options.headers = this.header;
        this.http.get(url, options).subscribe(res => success(res), error => {
            if (error.status == '401') {
                this.router.navigate(['/login']);
            } else if (failure != null) {
                failure(error);
            }
        });
    }

    post(url: string, data: any, success: any, failure: any) {
        this.header.set('Content-Type', 'application/json; charset=utf-8')
        this.http.post(url, data, { headers: this.header }).subscribe(res => success(res), error => {
            if (error.status == '401') {
                this.router.navigate(['/login']);
            } else if (failure != null) {
                failure(error);
            }
        })
    }
}